<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合伙企业名称')" prop="name">
            <el-autocomplete
              v-model="form.name"
              class="inline-input name"
              :fetch-suggestions="companyQuerySearch"
              :placeholder="$t('合伙企业名称')"
              :trigger-on-focus="false"
              :maxlength="100"
              @select="companyHandleSelect"
            >
              <template v-if="enableTyc" slot="append">
                <a @click="companyHandleSelect">{{ $t('查询工商信息') }}</a>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('执行事务合伙人')" prop="executivePartner">
            <el-input v-model="form.executivePartner" :placeholder="$t('执行事务合伙人')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('执行事务合伙人委派代表')" prop="appoints">
            <el-input v-model="form.appoints" :placeholder="$t('执行事务合伙人委派代表')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('成立时间')" prop="established">
            <DatePicker
              v-model="form.established"
              :placeholder="$t('成立时间')"
            />

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('企业统一社会信用代码')" prop="creditCode">
            <el-input v-model="form.creditCode" :placeholder="$t('企业统一社会信用代码')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('执照登记日期')" prop="registerDate">
            <DatePicker
              v-model="form.registerDate"
              :placeholder="$t('执照登记日期')"
            />

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合伙期限')" prop="partnershipTerm">
            <el-input v-model="form.partnershipTerm" :placeholder="$t('合伙期限')" :maxlength="50" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基本户')" prop="baseAccount">
            <el-input v-model="form.baseAccount" :placeholder="$t('基本户')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('经营场所')" prop="businessPlace">
            <el-input v-model="form.businessPlace" :placeholder="$t('经营场所')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('经营范围')" prop="businessRange">
            <el-input v-model="form.businessRange" :placeholder="$t('经营范围')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金管理人')" prop="gpId">
            <MainBodySelect
              v-model="form.gpId"
              parameters="manager"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否备案')" prop="record">
            <dict-select
              v-model="form.record"
              dictionary="yes_no_record"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>
      <div v-if="form.actStatus !== 'W'">
        <div class="area-header">
          <span class="area-header-title">{{ $t('股东信息') }}</span>
        </div>
        <div>
          <el-table :data="form.hhqyEquityStructures" class="nowrapTable formTable" border>
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('股东名称')" prop="name" align="center">
              <template slot-scope="scope">
                <el-autocomplete
                  v-model="scope.row.name"
                  :fetch-suggestions="(queryString, cg) => querySearch(queryString, cg, scope.$index)"
                  :placeholder="$t('股东名称')"
                  @select="shareholderOnSelect($event, scope.$index)"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('持股比例(%)')" prop="shareholdingRatio" align="center">
              <template slot-scope="scope">
                <Ratio v-model="scope.row.shareholdingRatio" :precision="2" :controls="false" :max="100" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('投资金额') + $t('金额单位')" prop="investAmount" align="center">
              <template slot-scope="scope">
                <Money v-model="scope.row.investAmount" unit="w" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('操作')" width="100" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="delShareholder(scope.$index)">{{ $t('删除') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="tol">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addShareholder">{{ $t("添加") }}</el-button>
          </div>
        </div>
      </div>
      <div v-if="form.actStatus === 'W' && form.hhqyEquityStructures && form.hhqyEquityStructures.length &gt; 0">
        <div class="area-header" style="margin-top: 10px;">
          <span class="area-header-title">{{ $t('股东信息') }}</span>
        </div>
        <el-table :data="form.hhqyEquityStructures" border>
          <el-table-column :label="$t('股东名称')" align="center" prop="name" />
          <el-table-column :label="$t('持股比例(%)')" align="center" prop="shareholdingRatio" />
          <el-table-column :label="$t('投资金额') + $t('金额单位')" align="center" prop="investAmount">
            <template slot-scope="scope">
              <span>{{ moneyFormat(scope.row.investAmount, 'w') }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="structuresTotal>0"
          :total="structuresTotal"
          :page.sync="structuresPage.pageNum"
          :limit.sync="structuresPage.pageSize"
          @pagination="findByHhqyId"
        />
      </div>
      <div v-if="form.actStatus === 'W' && form.hhqyChangeShareholders && form.hhqyChangeShareholders.length &gt; 0">
        <div class="area-header" style="margin-top: 10px;">
          <span class="area-header-title">{{ $t('下属合伙企业') }}</span>
        </div>
        <el-table :data="form.hhqyChangeShareholders" border>
          <el-table-column :label="$t('股东名称')" align="center" prop="hhqyChangeName" />
          <el-table-column :label="$t('持股比例(%)')" align="center" prop="shareholdingRatio" />
          <el-table-column :label="$t('投资金额') + $t('金额单位')" align="center" prop="investAmount">
            <template slot-scope="scope">
              <span>{{ moneyFormat(scope.row.investAmount, 'w') }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="subHhqyTotal>0"
          :total="subHhqyTotal"
          :page.sync="subHhqyPage.pageNum"
          :limit.sync="subHhqyPage.pageSize"
          @pagination="findSubHhqyByHhqyId"
        />
      </div>
      <!--文件-->
      <FileTable :list.sync="form.fileList" data-type="hhqy_base" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn v-if="!this.$route.query.id" ref="formBtn" :bus-data="form" has-permi="hhqy:base" :menu-key="menuKey" />
      <SaveBtn v-else has-permi="hhqy:base" :cancel-show="false" style="margin-top: 10px;" />
    </div>
  </div>
</template>

<script>
import { saveHhqyBase, getHhqyBase, getHhqyDetail, listHhqyBase, getHolderInfoByTycIdAndCompanyName } from '@/api/hhqy/base/hhqyBase'
import { companyListByName } from '@/api/company/base/companyBase'
import { findByHhqyId } from '@/api/hhqy/structure/hhqyEquityStructure'
import { findSubHhqyByHhqyId } from '@/api/hhqy/changehistory/hhqyChangeHistory'
import { Notification } from 'element-ui'
import MainBodySelect from '@/components/MainBodySelect'
    export default {
        components: {
          MainBodySelect
        },
        data() {
            return {
              enableTyc: undefined,
              otherBtnHide: false,
              // 菜单标识
              menuKey: 'hhqy_base',
                // 表单参数
                form: {},
                // 遮罩层
                loading: false,
              // 股东名称列表数据
              restaurants: [],
                // 表单校验
                rules: {
                  name: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], executivePartner: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], actTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ]
                },
              // 天眼查查询条件
              tycParam: {
                id: '',
                companyName: '',
                tycId: ''
              },
              // 股东信息查询分页
              structuresPage: {
                hhqyId: undefined,
                pageNum: 1,
                pageSize: 10
              },
              structuresTotal: 0,
              // 下属合伙企业查询分页
              subHhqyPage: {
                hhqyId: undefined,
                pageNum: 1,
                pageSize: 10
              },
              subHhqyTotal: 0
            }
        },
        created() {
        },
      mounted() {
        this.$bus.$emit('async_done')
        this.enableTyc = (window.localStorage.getItem('enableTyc') === 'true')
        listHhqyBase().then(response => {
          this.restaurants = response.rows.map((ele) => { return { value: ele.name, id: ele.id } })
        })
      },
      methods: {
            // 初始化数据
            init(data) {
              this.loading = true
                if (data != null && data.id !== undefined) {
                    getHhqyBase(data.id).then(response => {
                        this.form = response.data
                        if (this.form.actStatus === 'W') {
                          this.findSubHhqyByHhqyId()
                          this.findByHhqyId()
                        }
                      this.loading = false
                    })
                } else {
                    this.reset()
                  this.loading = false
                }
            },
            // 查询下属合伙企业
            findSubHhqyByHhqyId: async function() {
              this.subHhqyPage.hhqyId = this.form.id
              await findSubHhqyByHhqyId(this.subHhqyPage).then(response => {
                this.form.hhqyChangeShareholders = response.rows
                this.subHhqyTotal = response.total
              })
            },
            // 查询股东信息
            findByHhqyId: async function() {
              this.structuresPage.hhqyId = this.form.id
              await findByHhqyId(this.structuresPage).then(response => {
                this.form.hhqyEquityStructures = response.rows
                this.structuresTotal = response.total
              })
            },
            // 表单重置
            reset() {
                this.form = {
                  id: undefined,
                  name: undefined,
                  executivePartner: undefined,
                  appoints: undefined,
                  established: undefined,
                  creditCode: undefined,
                  registerDate: undefined,
                  partnershipTerm: undefined,
                  baseAccount: undefined,
                  businessPlace: undefined,
                  businessRange: undefined,
                  delFlag: undefined,
                  createBy: undefined,
                  updateBy: undefined,
                  createTime: undefined,
                  updateTime: undefined,
                  remark: undefined,
                  tycId: undefined,
                  gpId: undefined,
                  hhqyEquityStructures: []
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm: function(type) {
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                  if (valid) {
                    this.loading = true
                    saveHhqyBase(this.form).then(response => {
                      if (response.code === 200) {
                        this.form = response.data
                        // 点击的按钮是保存并启动流程
                        if (type === 'process') {
                          // 启动流程
                          this.startProcess(response.data.id)
                          // 点击的仅保存
                        } else {
                          this.msgSuccess(this.$t('保存成功'))
                          // 关闭form页面
                          this.closeForm()
                        }
                        resolve()
                      } else {
                        this.msgError(response.msg)
                        reject()
                      }
                      this.loading = false
                    })
                  } else {
                    reject()
                    this.locationError(document)
                  }
                })
              })
           },
        // 启动流程
        startProcess: function(dataId) {
          this.loading = false
          // 启动流程时候传入的参数
          const processData = {}
          // 待办标题
          processData.title = '「' + this.form.name + '」' + this.form.actTitle
          // 业务表名
          processData.dataTable = 'hhqy_base'
          // 业务ID
          processData.dataId = dataId
          // 业务表单地址(待办页面需要打开的页面)
          processData.formPath = '@/views/hhqy/base/hhqyBaseForm'
          processData.viewPath = '@/views/hhqy/base/hhqyBaseView'
          // 菜单标识(根据菜单标识判断的走哪个流程)
          processData.menuKey = this.menuKey
          this.startProcessByMenu(processData, () => {
            this.form.actStatus = 'D'
            this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
            this.closeForm()
          })
        },
          // 标的公司查询
          companyQuerySearch(queryString, cb) {
            companyListByName(queryString).then(res => {
              if (res.code === 200) {
                cb(res.data)
              }
            })
          },
          // 标的公司选择后事件
          companyHandleSelect(item) {
            this.loading = true
            var name = this.form.name
            if (name === '' || name === undefined) {
              Notification.error({
                title: this.$t('请先输入公司全称！')
              })
              this.loading = false
              return
            }
            this.resetForm()
            this.tycParam.id = this.form.id
            this.tycParam.tycId = item.id
            this.tycParam.name = name
            this.tycParam.orgType = item.type
            getHhqyDetail(this.tycParam).then(res => {
              if (res.code === 200) {
                if (res.msg === 'exist') {
                  this.form.mediationName = undefined
                  Notification.error({
                    title: this.$t('合伙企业全称已存在！')
                  })
                  this.loading = false
                } else if (res.msg === 'nofind') {
                  this.form.companyName = undefined
                  Notification.error({
                    title: this.$t('天眼查没有获取到该合伙企业信息！')
                  })
                  this.loading = false
                } else {
                  // 公司简称
                  this.form.name = name
                  // 企业统一社会信用代码
                  this.form.creditCode = res.data.creditCode
                  // 成立时间
                  this.form.established = res.data.setDate

                  this.form.businessRange = res.data.businessScope
                  // 天眼查ID
                  this.form.tycId = res.data.tycId

                  this.form.remark = res.data.remark

                   // 股东信息获取
                    getHolderInfoByTycIdAndCompanyName(item.id, name).then(res => {
                      this.form.hhqyEquityStructures = res.data
                        this.loading = false
                         this.msgSuccess(this.$t('已获取工商信息！'))
                    }).catch(() => {
                        this.loading = false
                         this.msgError(this.$t('获取失败'))
                    })
                }
              }
            })
          },
          // 初始化天眼查获取的数据
          resetForm() {
            this.form.name = undefined
            this.form.creditCode = undefined
            this.form.estiblishTime = undefined
            this.form.tycId = undefined
          },
        querySearch(queryString, cb, index) {
          var restaurants = this.restaurants
          var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
          if (results.length === 0) {
            this.form.hhqyEquityStructures[index].shareholderId = undefined
          }
          // 调用 callback 返回建议列表的数据
          cb(results)
        },
        createFilter(queryString) {
          return (restaurant) => {
            return (restaurant.value.toLowerCase().includes(queryString.toLowerCase()))
          }
        },
        shareholderOnSelect(val, index) {
          this.form.hhqyEquityStructures[index].shareholderId = val.id
        },
        addShareholder() {
          const row = {
            id: undefined,
            name: '',
            shareholdingRatio: undefined,
            investAmount: undefined
          }
          if (!(this.form.hhqyEquityStructures instanceof Array)) {
            this.$set(this.form, 'hhqyEquityStructures', [])
          }
          this.$nextTick(() => {
            this.form.hhqyEquityStructures.push(row)
          })
        },
        delShareholder(index) {
          this.form.hhqyEquityStructures.splice(index, 1)
        }
      }

    }
</script>
